// 站点配置管理
class SiteConfigManager {
  constructor() {
    this.defaultSites = [
      {
        site_domain: 'jarvis.myscrm.cn',
        site_name: 'Jarvis MySCRM',
        auth_type: 'localStorage',
        auth_key: 'jsso_ticket',
        enabled: true,
        description: '从localStorage获取jsso_ticket'
      }
    ];
  }

  // 获取所有站点配置
  async getSites() {
    const result = await chrome.storage.local.get(['sites']);
    return result.sites || this.defaultSites;
  }

  // 保存站点配置
  async saveSites(sites) {
    await chrome.storage.local.set({ sites });
  }

  // 添加新站点
  async addSite(site) {
    const sites = await this.getSites();
    const newSite = {
      ...site,
      enabled: true
    };
    sites.push(newSite);
    await this.saveSites(sites);
    return newSite;
  }

  // 更新站点
  async updateSite(domain, updates) {
    const sites = await this.getSites();
    const index = sites.findIndex(site => site.site_domain === domain);
    if (index !== -1) {
      sites[index] = { ...sites[index], ...updates };
      await this.saveSites(sites);
      return sites[index];
    }
    return null;
  }

  // 删除站点
  async deleteSite(domain) {
    const sites = await this.getSites();
    const filteredSites = sites.filter(site => site.site_domain !== domain);
    await this.saveSites(filteredSites);
  }

  // 获取启用的站点
  async getEnabledSites() {
    const sites = await this.getSites();
    return sites.filter(site => site.enabled);
  }

  // 根据当前域名获取站点配置
  async getSite(domain) {
    const sites = await this.getEnabledSites();
    return sites.find(site => domain.includes(site.site_domain));
  }

  // 验证站点配置
  validateSite(site) {
    const required = ['site_name', 'site_domain', 'auth_type', 'auth_key'];
    for (const field of required) {
      if (!site[field]) {
        throw new Error(`缺少必需字段: ${field}`);
      }
    }

    const validAuthTypes = ['localStorage', 'cookie', 'sessionStorage'];
    if (!validAuthTypes.includes(site.auth_type)) {
      throw new Error(`不支持的认证类型: ${site.auth_type}`);
    }

    return true;
  }
}

// 认证数据提取器
class AuthDataExtractor {
  static extract(siteConfig) {
    switch (siteConfig.auth_type) {
      case 'localStorage':
        return this.extractFromLocalStorage(siteConfig.auth_key);
      case 'cookie':
        return this.extractFromCookie(siteConfig.auth_key);
      case 'sessionStorage':
        return this.extractFromSessionStorage(siteConfig.auth_key);
      default:
        throw new Error(`不支持的认证类型: ${siteConfig.auth_type}`);
    }
  }

  static extractFromLocalStorage(key) {
    try {
      // 如果key包含点号，说明是链式访问，需要先获取父级key
      if (key.includes('.')) {
        const parentKey = key.split('.')[0];
        const value = localStorage.getItem(parentKey);
        console.log(`[AuthDataExtractor] localStorage.getItem('${parentKey}'):`, value);
        const result = this.extractNestedValue(value, key);
        console.log(`[AuthDataExtractor] 提取结果:`, result);
        return result;
      } else {
        const value = localStorage.getItem(key);
        console.log(`[AuthDataExtractor] localStorage.getItem('${key}'):`, value);
        const result = this.extractNestedValue(value, key);
        console.log(`[AuthDataExtractor] 提取结果:`, result);
        return result;
      }
    } catch (error) {
      console.error('从localStorage提取数据失败:', error);
      return null;
    }
  }

  static extractFromCookie(key) {
    try {
      const cookies = document.cookie.split(';');
      for (const cookie of cookies) {
        const [name, value] = cookie.trim().split('=');
        if (name === key) {
          return this.extractNestedValue(decodeURIComponent(value), key);
        }
      }
      return null;
    } catch (error) {
      console.error('从cookie提取数据失败:', error);
      return null;
    }
  }

  static extractFromSessionStorage(key) {
    try {
      const value = sessionStorage.getItem(key);
      return this.extractNestedValue(value, key);
    } catch (error) {
      console.error('从sessionStorage提取数据失败:', error);
      return null;
    }
  }

  // 支持链式获取字段值，如 tokens.access_token
  static extractNestedValue(value, key) {
    if (!value) return null;
    
    // 检查是否包含链式访问（如 tokens.access_token）
    if (key.includes('.')) {
      try {
        const parts = key.split('.');
        let result = value;
        
        // 尝试解析为JSON
        if (typeof result === 'string') {
          result = JSON.parse(result);
        }
        
        // 逐层访问（跳过第一个部分，因为已经在extractFromLocalStorage中处理了）
        for (let i = 1; i < parts.length; i++) {
          const part = parts[i];
          if (result && typeof result === 'object' && part in result) {
            result = result[part];
          } else {
            console.log(`[AuthDataExtractor] 链式访问失败，找不到字段: ${part}，当前对象:`, result);
            return null;
          }
        }
        
        console.log(`[AuthDataExtractor] 链式访问成功，最终结果:`, result);
        return result;
      } catch (error) {
        console.error('链式访问失败:', error);
        return null;
      }
    }
    
    return value;
  }
}

// 导出
window.SiteConfigManager = SiteConfigManager;
window.AuthDataExtractor = AuthDataExtractor;
